package com.systop.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alipay.api.domain.GoodsVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.systop.entity.Classify;
import com.systop.entity.Goods;
import com.systop.service.GoodsService;
import com.systop.service.OSSFileManage;
import com.systop.utils.FileUploadResult;
import com.systop.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/GoodsManage")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private OSSFileManage ossFileManage;

    @RequestMapping(value = "/showGoodsInfo",method = RequestMethod.POST)
    @ResponseBody
    //查询商品信息
    public Map<String,Object> showGoodsInfo(@RequestBody Map<String,Object> map){
        //输出返回值数据
        // System.out.println(map);
        //将JSON数据转换成java能识别的对象类数据
        Goods goods =
                JSON.parseObject(JSON.parse(JSON.toJSONString(map.get("goods"))).toString(),
                        new TypeReference<Goods>(){});
        //输出转化后数据
        // System.out.println(goods);
        // System.out.println("返回添加修改下拉框数据");
        //返回添加修改下拉框数据
        List<Classify> classifyList = goodsService.findAllClassifyName();
        map.put("classifyList",classifyList);
        // System.out.println("返回查询数据总条数");
        //返回查询数据总条数
        int pageCount = goodsService.countGoods(goods);
        map.put("pageCount",pageCount);
        //分页查询用索引
        goods.getClassify().setStart(
                (goods.getClassify().getStart()-1)
                        *goods.getClassify().getPageSize());
        // System.out.println(goods.getClassify().getStart());
        // System.out.println("查询商品数据");
        //查询商品数据
        List<Goods> goodsList = goodsService.showGoodsInfo(goods);
        if(CollectionUtils.isEmpty(goodsList) && goods.getClassify().getStart()>0){
            //设置当本页没有数据时返回上一页
            goods.getClassify().setStart(goods.getClassify().getStart()/goods.getClassify().getPageSize());
            map.put("goods",goods);
            return showGoodsInfo(map);
        }
        map.put("goodsList",goodsList);
        // System.out.println("返回页面数据");
        //返回页面查询数据
        return map;
    };

    //前台首页随机获取商品信息
    //前台首页获取最新商品信息
    @RequestMapping(value = "/getRandGoods",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getRandGoods(){
        Map<String,Object> map = new HashMap<>();
        List<Goods> randGoodsList = goodsService.getRandGoods();
        List<Goods> newGoodsList = goodsService.getNewGoods();
        map.put("randGoodsList",randGoodsList);
        map.put("newGoodsList", newGoodsList);
        return map;
    }

    //前台分类页获取所有商品分类信息
    @RequestMapping(value = "/getAllClassAndGoodsInfo",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> getAllClassAndGoodsInfo(){
        Map<String,Object> map = new HashMap<>();
        List<Goods> AllGoodsAndClassifyList = goodsService.getAllClassAndGoodsInfo();
        List<Classify> classifyList = goodsService.findAllClassifyName();
        map.put("AllGoodsAndClassifyList",AllGoodsAndClassifyList);
        map.put("classifyList",classifyList);
        return map;
    };

    //添加商品数据
    @RequestMapping(value = "/addGoods",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> addGoods(@RequestParam("file") MultipartFile file,
                                       @RequestParam("goods") String goods){
        System.out.println(goods);
        //将JSON数据转换成java能识别的对象类数据
        Goods goodsPojo =
                JSON.parseObject(JSON.parse(JSON.toJSONString(goods)).toString(),
                        new TypeReference<Goods>(){});
        //定义键值对返回数据
        Map<String,Object> map = new HashMap<>();
        int i = 0;
        //检查数据库是否存在相同名称商品
        int exist = goodsService.findGoodsBygoodsName(goodsPojo);
        map.put("exist", exist);
        if(exist == 0){
            //上传图片到OSS服务器上
            FileUploadResult result = ossFileManage.upload(file);
            //如果上传成功执行向数据库中添加数据的方法
            if(result.getStatus()=="done"){
                //将上传成功后返回的地址存入到数据库当中
                goodsPojo.setGoodsImg(result.getName());
                //执行数据库中添加数据的方法
                i = goodsService.addGoods(goodsPojo);
            }else if(result.getStatus()=="error"){
                map.put("msg",result.getStatus()+",上传失败,数据错误");
                return map;
            }
            map.put("addSuccNum",i);
            if(i>0){
                map.put("msg", "添加成功!");
            }else{
                map.put("msg","添加失败,数据错误");
                return map;
            }
        }else{
            map.put("msg","添加失败,商品已存在");
        }
        return map;
    };

    //根据id删除指定对象方法
    @RequestMapping(value = "/delGoods",method = RequestMethod.DELETE)
    @ResponseBody
    public Map<String,Object> delGoods(Goods goods){
        System.out.println(goods);
        //定义键值对返回数据
        Map<String,Object> map = new HashMap<>();
        int exist = goodsService.findOrder(goods);
        System.out.println(exist);
        if(exist==0){
            //如果存在图片就先删除OSS中上传的图片
            if(goods.getGoodsImg() !=null && goods.getGoodsImg().length()>0){
                String url = goods.getGoodsImg();
                url = url.replace("https://oss-container.oss-cn-beijing.aliyuncs.com/","");
                //判断路径中是否存在?
                if(url.indexOf("?")!=-1){
                    url = url.substring(0,url.indexOf("?"));
                    FileUploadResult result = ossFileManage.delete(url);
                }
            }
            int i = goodsService.delGoods(goods);
            map.put("delSuccNum",i);
            if(i>0){
                map.put("msg", "删除成功!");
            }else{
                map.put("msg","删除失败,用户不存在");
            }
        }else{
            map.put("msg","订单中存在相应商品");
        }
        return map;
    };

    //更新数据方法
    @RequestMapping(value = "/udpGoods",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> udpGoods(@RequestBody Goods goods){
        System.out.println(goods);
        Map<String,Object> map = new HashMap<>();
        int i = 0;
        //根据名称判断是否已存在响应数据
        int exist = goodsService.findDataUnlessId(goods);
        map.put("exist", exist);
        if(exist == 0){
            //执行更新方法
            i = goodsService.udpGoods(goods);
            map.put("udpSuccNum",i);
            if(i>0){
                map.put("msg", "修改成功!");
            }else{
                map.put("msg","修改失败,商品不存在");
            }
        }else{
            map.put("msg","修改失败,商品已存在,或有类似商品");
        }
        return map;
    }

    //更新数据方法(带文件)
    @RequestMapping(value = "/udpGoodsWithImg",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> udpGoodsWithImg(@RequestParam("file") MultipartFile file,
                           @RequestParam("goods") String goods){
        System.out.println(goods);
        Goods goodsPojo = JSON.parseObject(JSON.parse(JSON.toJSONString(goods)).toString(),
                new TypeReference<Goods>(){});
        System.out.println(goodsPojo);
        Map<String,Object> map = new HashMap<>();
        FileUploadResult result = new FileUploadResult();
        int i = 0;
        //根据名称判断是否已存在响应数据
        int exist = goodsService.findDataUnlessId(goodsPojo);
        map.put("exist", exist);
        if(exist == 0){
            //如果存在图片就先删除OSS中上传的图片
            if(!goodsPojo.getGoodsImg().equals("")){
                System.out.println("进入删除OSS图片方法");
                String url = goodsPojo.getGoodsImg();
                url = url.replace("https://oss-container.oss-cn-beijing.aliyuncs.com/","");
                //判断路径中是否存在?
                if(url.indexOf("?")!=-1){
                    url = url.substring(0,url.indexOf("?"));
                    result = ossFileManage.delete(url);
                }
            }
            //如果删除成功后就再添加一个图片
            if(result.getStatus()=="removed" || goodsPojo.getGoodsImg().equals("")){
                //上传图片到OSS服务器上
                result = ossFileManage.upload(file);
                if(result.getStatus()=="done"){
                    goodsPojo.setGoodsImg(result.getName());
                    i = goodsService.udpGoods(goodsPojo);
                }else if(result.getStatus()=="error"){
                    map.put("msg",result.getStatus()+",上传失败,数据错误");
                    return map;
                }
            }else{
                map.put("msg","原图删除失败,数据错误");
                return map;
            }
            map.put("udpSuccNum",i);
            if(i>0){
                map.put("msg", "修改成功!");
            }else{
                map.put("msg","修改失败,数据错误");
                return map;
            }
        }else{
            map.put("msg","修改失败,商品已存在,或有类似商品");
        }
        return map;
    }

    @GetMapping("/searchForGoods")
    @ResponseBody
    public R searchForGoods(String goodsName,boolean isClassify,Long classifyId){
        //分类部分访问查询数据
        if (isClassify){
            if (classifyId == null)
                return R.error();

            List<Goods> goodsList = goodsService.list(new QueryWrapper<Goods>()
                    .eq("classify_id", classifyId));
            return R.ok().put("goodsList",goodsList);
        }

        if (goodsName == null || goodsName.equals(""))
            return R.error();

        //搜索部分访问查询数据
        List<Goods> goodsList = goodsService.list(new QueryWrapper<Goods>()
                .like("goods_name", goodsName));
        return R.ok().put("goodsList",goodsList);
    }
}
